package cn.csc.module.shoppingCard.controller.app.transaction;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.module.order.api.item.OrderItemApi;
import cn.csc.module.order.api.item.dto.OrderItemRespDTO;
import cn.csc.module.shoppingCard.controller.admin.transaction.vo.CardTransactionRespVO;
import cn.csc.module.shoppingCard.convert.transaction.CardTransactionConvert;
import cn.csc.module.shoppingCard.dal.dataobject.transaction.CardTransactionDO;
import cn.csc.module.shoppingCard.service.transaction.CardTransactionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;

@Api(tags = "用户APP - 交易记录")
@RestController
@RequestMapping("/shoppingCard/card-transaction")
@Validated
public class AppCardTransactionController {

    @Resource
    private CardTransactionService cardTransactionService;

    @Autowired
    private OrderItemApi orderItemApi;


    /**
     * 通过carId获得交易记录列表
     */
    @GetMapping("/getByCardId")
    @ApiOperation("通过carId获得交易记录列表")
    @ApiImplicitParam(name = "cardId", value = "购物卡编号", required = true, example = "1024", dataTypeClass = BigInteger.class)
    public CommonResult<List<CardTransactionRespVO>> getByCardId(@RequestParam("cardId") BigInteger cardId) {
        List<CardTransactionDO> list = cardTransactionService.getByCardId(cardId);
        if (CollectionUtils.isAnyEmpty(list)){
            return success();
        }
        List<BigInteger> ids = list.stream().map(CardTransactionDO::getRelatedOrderItem).collect(Collectors.toList());
        List<OrderItemRespDTO> itemRespDTOS = orderItemApi.getByIds(ids).getCheckedData();
        Map<BigInteger, OrderItemRespDTO> dtoMap = CollectionUtils.convertMap(itemRespDTOS, OrderItemRespDTO::getId);
        List<CardTransactionRespVO> respVOS = CardTransactionConvert.INSTANCE.convertList(list);
        respVOS.forEach(ct -> ct.setOrderItem(dtoMap.get(ct.getRelatedOrderItem())));

        return success(respVOS);
    }



}
